package org.meow.interception;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.meow.constant.MsgConstant;
import org.meow.exception.AuthException;
import org.meow.properties.JwtProperties;
import org.meow.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * &#064;Date: 24/05/14-17:00
 * &#064;Description:
 */
@Component
public class JwtCommonItcpt implements HandlerInterceptor {
  @Autowired
  private JwtProperties jwtProperties;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    if (!(handler instanceof HandlerMethod))
      return true;
    String token = request.getHeader(jwtProperties.getTokenName());
    try {
      JwtUtil.parseJwt(jwtProperties.getAdminSecretKey(), token);
    } catch (Exception exception) {
      try {
        Claims claims = JwtUtil.parseJwt(jwtProperties.getUserSecretKey(), token);
      } catch (Exception ex) {
        response.setStatus(401);
        throw new AuthException(ex instanceof ExpiredJwtException
            ? MsgConstant.TOKEN_EXPIRED : MsgConstant.TOKEN_ERROR);
      }
    }
    return true;
  }
}
